/**
 * 创建数据库
 */
function prepareDb(version, callback) {
    if (!window.openDatabase) {
        alert("浏览器不支持！");
        return;
    }
    var db = openDatabase('roster', '', 'Offline roster users storage', 5 * 1024 * 1024);
    if (db.version !== version) {
        reloadDb(db, version, callback);
    } else {
        callback();
    }
    return db;
}

/**
 * 刷新数据库数据
 */
function reloadDb(db, version, callback) {
    $.get("/users.json", function(data) {
        db.changeVersion(db.version, version, function(t) {
            t.executeSql('DROP TABLE IF EXISTS users');
            t.executeSql('CREATE TABLE users (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,cnname VARCHAR(50),workno INTEGER,email VARCHAR(50),phone VARCHAR(10),dept VARCHAR(50),py VARCHAR(10),duty VARCHAR(50))');
            $(data).each(function(i, u) {
                t.executeSql('INSERT INTO users(cnname,workno,email,phone,dept,py,duty) VALUES(?,?,?,?,?,?,?)',
                        [u.cnname, u.workno, u.email, u.phone, u.dept, u.py, u.duty]);
            });
            alert("数据已更新！");
            callback();
        }, function(e) {
            alert("浏览器错误" + e);
            console.log(e);
        }, $.noop);
    });
}
function buildView() {
    Ext.setup({
        tabletStartupScreen: '/images/tablet_startup.png',
        phoneStartupScreen: '/images/phone_startup.png',
        icon: '/images/icon.png',
        glossOnIcon: false,

        onReady: function() {
            var searchField = new Ext.form.Search({
                width: '70%',
                placeHolder: '搜索分机号/拼音/姓名',
                autoCapitalize: false,
                autoComplete: true,
                listeners:{
                    keyup:function() {
                        var key = this.getValue();
                        store.clearFilter();
                        if (/^\d+$/.test(key)) {
                            store.filter('phone LIKE ? OR workno = ?', [key + "%", key]);
                        } else if (/^[a-zA-Z]+$/.test(key)) {
                            store.filter('py LIKE ? OR email LIKE ?', [key + "%", key + "%"]);
                        } else if (/[\u4e00-\u9fa5]+/.test(key)) {
                            store.filter('cnname LIKE ? OR dept LIKE ?', [key + "%", "%" + key + "%"]);
                        }
                    }
                }
            });

            Ext.regModel('User', {
                fields: ['id', 'cnname', 'workno', 'phone', 'dept', 'duty', 'email']
            });
            var store = new Ext.data.JsonStore({
                model  : 'User',
                sorters: 'id',
                remoteFilter: true,
                autoLoad: true,

                proxy: {
                    type: 'webdb',
                    dbVersion: '',
                    dbName: 'roster',
                    dbTable: 'users',
                    pkField: 'id',
                    limit: 15
                }
            });
            var list = new Ext.List({
                fullscreen: false,
                grouped: false,
                indexBar: false,
                itemTpl: '<div class="users-list"><strong>{cnname}</strong><span class="phone">{phone}</span></div>',
                store: store,
                loadingText: '搜索中...',
                listeners:{
                    selectionchange: function(sel, records) {
                        if (records[0] !== undefined) {
                            var newCard = new Ext.Panel({
                                scroll: 'vertical',
                                dockedItems: [
                                    {
                                        dock: 'top',
                                        xtype: 'toolbar',
                                        title: '员工快捷查询',
                                        items: [
                                            {
                                                ui: 'back',
                                                text: '返回',
                                                scope: newCard,
                                                handler: function() {
                                                    app.setActiveItem(mainPanel, {
                                                        type: 'slide',
                                                        reverse: true,
                                                        scope: this,
                                                        after: function() {
                                                            this.destroy();
                                                        }
                                                    });
                                                }
                                            }
                                        ]
                                    }
                                ],
                                items: [
                                    {
                                        styleHtmlContent: false,
                                        tpl: '<ul class="roster">' +
                                                '<li>姓名：{cnname}</li>' +
                                                '<li>工号：{workno}</li>' +
                                                '<li>部门：{dept}</li>' +
                                            //'<li>职位：{duty}</li>' +
                                                '<li>分机：{phone}</li>' +
                                                '<li>邮箱：<a href="mailto:{email}">{email}</a></li>' +
                                                '</ul>',
                                        data: records[0].data
                                    }
                                ]
                            });
                            app.setActiveItem(newCard, 'slide');
                        }
                    }
                }
            });
            var mainPanel = new Ext.Panel({
                layout: 'fit',
                items: [list],
                dockedItems:[
                    {
                        dock: 'top',
                        xtype: 'toolbar',
                        title: '员工快捷查询',
                        layout: {
                            pack: 'right'
                        },
                        items: [
                            {
                                text: '关于',
                                handler: function() {
                                    Ext.Msg.alert('关于', '作者：葛亮<br/>数据日期：' + nowVersion);
                                }
                            }
                        ]
                    },
                    {
                        dock: 'top',
                        xtype: 'toolbar',
                        ui: 'light',
                        layout: {
                            pack: 'center'
                        },
                        items: [
                            searchField
                        ]
                    }
                ]

            });
            var app = new Ext.Panel({
                fullscreen: true,
                layout: 'card',
                items:[mainPanel]
            });
        }
    });
}
var db = prepareDb(nowVersion, buildView);